<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, ref, unref } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
import { useI18n } from '@/hooks/web/useI18n'
import { delMenuItemApi, getMenuListApi, getMenuShowApi, editMenuItemApi } from '@/api/menu'
import {
  ElButton,
  ElInput,
  ElPopconfirm,
  ElTable,
  ElTableColumn,
  ElTag,
  ElSelect,
  ElMessage,
  ElOption
} from 'element-plus'
import IconPicker from '@/components/IconPicker/index.vue'
import AddButtonPermission from './AddButtonPermission.vue'
import { BaseButton } from '@/components/Button'
import { generateUUID } from '@/utils'

const { t } = useI18n()

const { required } = useValidator()

const props = defineProps({
  currentRow: {
    type: Object as PropType<any>,
    default: () => null
  },
  actionType: {
    type: String,
    default: ''
  }
})

const methodOptions = ref<any[]>([
  { label: 'GET', value: 'GET' },
  { label: 'POST', value: 'POST' },
  { label: 'PUT', value: 'PUT' },
  { label: 'DELETE', value: 'DELETE' }
])

const handleClose = async (tag: any) => {
  const formData = await getFormData()
  if (props.actionType === 'edit') {
    await delMenuItemApi({ id: tag.id })
    await getDetailData({ id: props.currentRow.id })
    ElMessage.success(t('purchase.logistics.deleteSuccess'))
  } else {
    // 删除对应的权限
    setValues({
      permission: formData?.permission?.filter((v: any) => v.id !== tag.id)
    })
  }
}

const handleEdit = async (row: any) => {
  // 深拷贝当前行数据到编辑行
  permissionEditingRow.value = { ...row }
}

const handleSave = async () => {
  const formData = await getFormData()
  if (props.actionType === 'edit') {
    await editMenuItemApi({ ...permissionEditingRow.value })
    await getDetailData({ id: props.currentRow.id })
    permissionEditingRow.value = null // 重置编辑状态
    ElMessage.success('更新成功')
  } else {
    const index = formData?.permission?.findIndex((x) => x.id === permissionEditingRow.value.id)
    if (index !== -1) {
      formData.permission[index] = { ...permissionEditingRow.value }
      permissionEditingRow.value = null // 重置编辑状态
    }
  }
}
const dealStatus = async (val: Record<string, any>) => {
  if (val.type === 2) {
    setSchema([
      {
        field: 'components',
        path: 'componentProps.disabled',
        value: false
      }
    ])
    // setSchema([
    //   {
    //     field: 'redirect',
    //     path: 'componentProps.disabled',
    //     value: true
    //   }
    // ])
  } else {
    setSchema([
      {
        field: 'components',
        path: 'componentProps.disabled',
        value: true
      }
    ])
    // setSchema([
    //   {
    //     field: 'redirect',
    //     path: 'componentProps.disabled',
    //     value: false
    //   }
    // ])
    if (val.parentId === void 0) {
      setValues({
        components: '#'
      })
    } else {
      setValues({
        components: '##'
      })
    }
  }
}
const showDrawer = ref(false)
// 存储正在编辑的行的数据
const permissionEditingRow = ref<any>(null)

const formSchema = reactive<FormSchema[]>([
  {
    field: 'type',
    label: '菜单类型',
    component: 'RadioButton',
    value: 1,
    colProps: {
      span: 24
    },
    componentProps: {
      options: [
        {
          label: '目录',
          value: 1
        },
        {
          label: '菜单',
          value: 2
        }
      ],
      on: {
        change: async (val: number) => {
          const formData = await getFormData()
          if (val === 2) {
            setSchema([
              {
                field: 'components',
                path: 'componentProps.disabled',
                value: false
              }
            ])
            // setSchema([
            //   {
            //     field: 'redirect',
            //     path: 'componentProps.disabled',
            //     value: true
            //   }
            // ])
            // setValues({
            //   components: unref(cacheComponent)
            // })
          } else {
            setSchema([
              {
                field: 'components',
                path: 'componentProps.disabled',
                value: true
              }
            ])
            // setSchema([
            //   {
            //     field: 'redirect',
            //     path: 'componentProps.disabled',
            //     value: false
            //   }
            // ])
            if (formData.parentId === void 0) {
              setValues({
                components: '#'
              })
            } else {
              setValues({
                components: '##'
              })
            }
          }
        }
      }
    }
  },
  {
    field: 'parent_id',
    label: '父级菜单',
    component: 'TreeSelect',
    componentProps: {
      nodeKey: 'id',
      props: {
        label: 'title',
        value: 'id',
        children: 'children'
      },
      highlightCurrent: true,
      expandOnClickNode: false,
      checkStrictly: true,
      checkOnClickNode: true,
      clearable: true,
      on: {
        change: async (val: number) => {
          const formData = await getFormData()
          if (val && formData.type === 1) {
            setValues({
              components: '##'
            })
          } else if (!val && formData.type === 1) {
            setValues({
              components: '#'
            })
          } else if (formData.type === 2) {
            setValues({
              components: unref(cacheComponent) ?? ''
            })
          }
        }
      }
    },
    optionApi: async () => {
      const res = await getMenuListApi()
      res.data.list
        ? res.data.list.unshift({
            id: 0,
            title: '顶级目录'
          })
        : []
      return res.data.list || []
    }
  },
  {
    field: 'name',
    label: t('menu.menuName'),
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'components',
    label: '组件',
    component: 'Input',
    value: '#',
    componentProps: {
      disabled: true,
      placeholder: '#为顶级目录，##为子目录',
      on: {
        change: (val: string) => {
          cacheComponent.value = val
        }
      }
    },
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'components_name',
    label: t('menu.name'),
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'icon',
    label: t('menu.icon'),
    formItemProps: {
      slots: {
        default: (data: any) => <IconPicker v-model={data.icon} popoverWidth={450} />
      }
    }
  },
  {
    field: 'redirect',
    label: '重定向路径',
    component: 'Input'
  },
  {
    field: 'url',
    label: t('menu.path'),
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'active_menu',
    label: t('menu.activeMenu'),
    component: 'Input'
  },
  {
    field: 'status',
    label: t('menu.status'),
    component: 'Select',
    value: 1,
    componentProps: {
      options: [
        {
          label: t('userDemo.disable'),
          value: 0
        },
        {
          label: t('userDemo.enable'),
          value: 1
        }
      ]
    },
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'sort',
    label: '排序',
    value: 1,
    component: 'InputNumber',
    componentProps: {
      min: 1
    },
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'permission',
    label: t('menu.permission'),
    component: 'CheckboxGroup',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: (data: any) => (
          <>
            <BaseButton
              class="m-t-5px"
              type="primary"
              size="small"
              onClick={() => {
                showDrawer.value = true
              }}
            >
              添加权限
            </BaseButton>
            <ElTable data={data?.permission}>
              <ElTableColumn type="index" prop="id" />
              <ElTableColumn
                prop="name"
                label="名称"
                v-slots={{
                  default: ({ row }: any) =>
                    permissionEditingRow.value && permissionEditingRow.value.id === row.id ? (
                      <ElInput v-model={permissionEditingRow.value.name} size="small" />
                    ) : (
                      <span>{row.name}</span>
                    )
                }}
              />
              <ElTableColumn
                prop="btnkey"
                label="权限字符"
                v-slots={{
                  default: ({ row }: any) =>
                    permissionEditingRow.value && permissionEditingRow.value.id === row.id ? (
                      <ElInput v-model={permissionEditingRow.value.btnkey} size="small" />
                    ) : (
                      <span>{row.btnkey}</span>
                    )
                }}
              />
              <ElTableColumn
                prop="method"
                label="请求方式"
                v-slots={{
                  default: ({ row }: any) =>
                    permissionEditingRow.value && permissionEditingRow.value.id === row.id ? (
                      <ElSelect v-model={permissionEditingRow.value.method} size="small">
                        {methodOptions.value.map((item: Record<string, any>) => (
                          <ElOption key={item.label} label={item.label} value={item.value} />
                        ))}
                      </ElSelect>
                    ) : (
                      <ElTag class="mr-1" key={row.method}>
                        {row.method}
                      </ElTag>
                    )
                }}
              />
              <ElTableColumn
                prop="route"
                label="接口地址"
                v-slots={{
                  default: ({ row }: any) =>
                    permissionEditingRow.value && permissionEditingRow.value.id === row.id ? (
                      <ElInput v-model={permissionEditingRow.value.route} size="small" />
                    ) : (
                      <span>{row.route}</span>
                    )
                }}
              />
              <ElTableColumn
                label="操作"
                width="180"
                v-slots={{
                  default: ({ row }: any) =>
                    permissionEditingRow.value && permissionEditingRow.value.id === row.id ? (
                      <ElButton size="small" type="primary" onClick={handleSave}>
                        确定
                      </ElButton>
                    ) : (
                      <>
                        <ElButton size="small" type="primary" onClick={() => handleEdit(row)}>
                          编辑
                        </ElButton>
                        <ElPopconfirm
                          title="Are you sure to delete this?"
                          onConfirm={() => handleClose(row)}
                        >
                          {{
                            reference: () => (
                              <ElButton size="small" type="danger">
                                删除
                              </ElButton>
                            )
                          }}
                        </ElPopconfirm>
                      </>
                    )
                }}
              />
            </ElTable>
          </>
        )
      }
    }
  },
  {
    field: 'is_hide',
    label: t('menu.hidden'),
    component: 'Switch',
    componentProps: {
      activeValue: 1,
      inactiveValue: 0
    }
  },
  {
    field: 'is_display',
    label: t('menu.alwaysShow'),
    component: 'Switch',
    componentProps: {
      activeValue: 1,
      inactiveValue: 0
    }
  },
  {
    field: 'is_alive',
    label: t('menu.noCache'),
    component: 'Switch',
    value: 1,
    componentProps: {
      activeValue: 1,
      inactiveValue: 0
    }
  },
  {
    field: 'is_multiple',
    label: t('menu.breadcrumb'),
    component: 'Switch',
    componentProps: {
      activeValue: 1,
      inactiveValue: 0
    }
  }
])

const rules = reactive({
  component: [required()],
  path: [required()],
  'meta.title': [required()]
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose, setSchema } = formMethods

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    return formData
  }
}

const getDetailData = async (row: Record<string, any>) => {
  const resp = await getMenuShowApi({ id: row.id })
  await setValues(resp.data, true)
  dealStatus(resp.data)
}
const cacheComponent = ref('')

defineExpose({
  submit,
  getDetailData
})

const confirm = async (data: any) => {
  const formData = await getFormData()
  if (props.actionType === 'edit') {
    await getDetailData({ id: props.currentRow.id })
  } else {
    setValues({
      permission: [...(formData?.permission || []), { id: generateUUID(), ...data }]
    })
  }
}
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="formSchema" />
  <AddButtonPermission
    v-model="showDrawer"
    :currentRow="props.currentRow"
    :actionType="props.actionType"
    @confirm="confirm"
  />
</template>
